/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable react/no-did-mount-set-state */
/* eslint-disable react/no-unused-state */
import React from 'react'
import E from 'wangeditor'
import {
  Button,
  Input,
  message,
  Upload,
  Popover,
  Radio,
  Row,
  Tag,
  Form,
} from 'antd'
import './index.scss'
import SimpleMDE from 'simplemde'
import 'simplemde/dist/simplemde.min.css'
import { publishArticle, updateArticle } from '@/api/article'
import { UploadOutlined, PlusOutlined } from '@ant-design/icons'
import { upload } from '@/api/index'
import Store from '@/store/index'
import { withRouter } from 'react-router-dom'
import marked from 'marked'
import highlight from 'highlight.js'
import { getEmojiList } from '@/api/emoji'
interface IProps {
  history?: any
}
interface IState {
  editor: any
  form: any
  fileList: any[]
  file2List: any[]
  editTools: string
  switchContent: string
  status: string
  emojiList: any[]
  imgUrl: string
  tags: any[]
  inputVisible: boolean
  inputValue: string
}
const { TextArea } = Input
class Publish extends React.Component<IProps, IState> {
  smde: any
  saveInputRef: React.RefObject<any>
  constructor(props) {
    super(props)
    this.saveInputRef = React.createRef()
    this.state = {
      editor: {},
      form: {},
      fileList: [], // 文件列表
      file2List: [],
      editTools: 'text', // text 富文本编辑器  marked marked编辑器
      imgUrl: '',
      switchContent: '切换为Markedown编辑器',
      status: 'add', // 默认新增
      emojiList: [],
      tags: ['Tag 1', 'Tag 2', 'Tag 3'],
      inputVisible: false,
      inputValue: '',
    }
  }
  componentDidMount() {
    const editor = new E('#div1')
    editor.config.uploadImgServer = '/api/uploadFile'
    editor.config.uploadFileName = 'file'
    editor.highlight = highlight
    editor.config.colors = [
      '#000000',
      '#eeece0',
      '#1c487f',
      '#4d80bf',
      'red',
      'green',
      'skyblue',
    ]
    editor.create()
    this.setState({ editor })
    this.getEmojiList().then(res => {
      console.log('哈哈哈哈哈')
      editor.config.emotions = [
        {
          title: '默认', // tab 的标题
          type: 'image', // 'emoji' 或 'image' ，即 emoji 形式或者图片形式
          content: this.state.emojiList,
        },
        {
          title: 'emoji', // tab 的标题
          type: 'emoji', // 'emoji' / 'image'
          // emoji 表情，content 是一个数组即可
          content:
            '😀 😃 😄 😁 😆 😅 😂 😊 😇 🙂 🙃 😉 😓 😪 😴 🙄 🤔 😬 🤐'.split(
              /\s/
            ),
        },
      ]
    })

    //来一个marked编辑器
    this.smde = new SimpleMDE({
      element: document.getElementById('editor'),
      autofocus: true,
      autosave: true,
      previewRender: function (plainText) {
        return marked(plainText, {
          renderer: new marked.Renderer(),
          gfm: true,
          pedantic: false,
          sanitize: false,
          tables: true,
          breaks: true,
          smartLists: true,
          smartypants: true,
          highlight: function (code) {
            return highlight.highlightAuto(code).value
          },
        })
      },
    })

    //检查是不是编辑
    console.log(this.props.history)
    if (this.props.history.location.state?.article) {
      console.log('现在是编辑状态')
      // 如果是
      if (this.props.history.location.state.article.editType) {
        // 判断编辑器类型
        this.setState({
          editTools: 'marked',
          switchContent: '切换为富文本编辑器',
        })
        this.smde.value(this.props.history.location.state.article.content)
      } else {
        editor.txt.html(this.props.history.location.state.article.content)
      }

      this.setState({
        form: {
          ...this.state.form,
          title: this.props.history.location.state.article.title,
          descripition: this.props.history.location.state.article.descripition,
        },
        status: 'edit', // 改为编辑状态
        fileList: [{ url: this.props.history.location.state.article.imgUrl }],
        imgUrl: this.props.history.location.state.article.imgUrl,
      })
    }
  }
  getEmojiList = async () => {
    const res: any = await getEmojiList()
    if (res.code === 200) {
      res.rows.forEach(item => {
        item.alt = item.name
        item.src = item.url
      })
      this.setState({ emojiList: res.rows })
    }
    return res
  }
  componentWillUnmount() {
    this.state.editor.destroy()
    this.setState({ editor: null })
  }
  publish = async () => {
    if (!this.state.form.title) {
      message.error('请输入文章标题')
      return
    } else if (!this.state.imgUrl) {
      message.error('请上传主页背景图')
      return
    } else if (!this.state.form.descripition) {
      message.error('请输入文章描述')
      return
    } else if (
      this.state.editTools == 'text'
        ? !this.state.editor.txt.html()
        : !this.smde.value()
    ) {
      message.error('请输入文章内容')
      return
    }
    const params = {
      ...this.state.form,
      imgUrl: this.state.fileList[0].url,
      userId: Store.userInfo.userId,
      createBy: Store.userInfo.nickName,
      content:
        this.state.editTools === 'text'
          ? this.state.editor.txt.html()
          : this.smde.value(),
      editType: this.state.editTools === 'text' ? 0 : 1,
    }
    if (this.state.status == 'add') {
      // 判断是编辑 还是修改
      const res: any = await publishArticle(params)
      if (res.code === 200) {
        message.success('发布成功！')
        this.setState({ form: {}, fileList: [] })
      } else {
        message.error('发布失败！！！')
      }
    } else {
      params.id = this.props.history.location.state.article.id
      const res: any = await updateArticle(params)
      if (res.code === 200) {
        message.success('修改成功！')
        this.setState({ form: {}, fileList: [] })
        this.props.history.goBack()
      } else {
        message.error('修改失败！！！')
      }
    }

    console.log(this.state.editor.txt.text())
  }
  titleChange = e => {
    this.setState(state => ({
      form: { ...state.form, title: e.target.value },
    }))
  }
  descripitionChange = e => {
    this.setState(state => ({
      form: { ...state.form, descripition: e.target.value },
    }))
  }
  upload = async e => {
    const file = new FormData()
    file.append('file', e.file)
    const res: any = await upload(file)
    if (res.errno == 0) {
      this.setState({
        fileList: [
          {
            uid: e.file.uid,
            name: e.file.name,
            status: 'done',
            url: res.data[0].url,
          },
        ],
        imgUrl: res.data[0].url,
      })
    }
    console.log(res)
    console.log(e)
  }
  deleteFile = e => {
    this.setState({ fileList: [] })
    console.log(e)
  }
  uploadMdChange = e => {
    console.log(e, 888)
  }
  toHome = () => {
    //回到主页
    this.props.history.push('/')
  }
  switchEditor = () => {
    // 切换编辑器
    if (this.state.editTools == 'text') {
      this.setState({
        editTools: 'marked',
        switchContent: '切换为富文本编辑器',
      })
    } else {
      this.setState({ editTools: 'text', switchContent: '切换为marked编辑器' })
    }
  }
  handleClose = removedTag => {
    const tags = this.state.tags.filter(tag => tag !== removedTag)
    console.log(tags)
    this.setState({ tags })
  }
  forMap = tag => {
    const tagElem = (
      <Tag
        closable
        onClose={e => {
          e.preventDefault()
          this.handleClose(tag)
        }}
      >
        {tag}
      </Tag>
    )
    return (
      <span key={tag} style={{ display: 'inline-block' }}>
        {tagElem}
      </span>
    )
  }
  showInput = () => {
    this.setState({ inputVisible: true })
  }
  handleInputChange = e => {
    this.setState({ inputValue: e.target.value })
  }
  handleInputConfirm = () => {
    const { inputValue } = this.state
    let { tags } = this.state
    if (inputValue && tags.indexOf(inputValue) === -1) {
      tags = [...tags, inputValue]
    }
    console.log(tags)
    this.setState({
      tags,
      inputVisible: false,
      inputValue: '',
    })
  }
  render() {
    const tagChild = this.state.tags.map(this.forMap)
    return (
      <div className='publish-content'>
        <div className='title-bar'>
          <div className='left'>
            <div>
              <Input
                placeholder='文章标题'
                value={this.state.form.title}
                onChange={this.titleChange}
              />
            </div>
            <Upload
              action='#'
              listType='picture'
              fileList={this.state.fileList}
              maxCount={1}
              customRequest={this.upload}
              onRemove={this.deleteFile}
              className='upload-btn'
            >
              <Button icon={<UploadOutlined />}>上传</Button>
            </Upload>
            {this.state.fileList.length == 0 && (
              <div className='info'>请上传主页背景图</div>
            )}
          </div>
          <div className='right'>
            <span className='switch'>
              <Popover content={this.state.switchContent} title=''>
                <img
                  src={require('../../assets/images/switch.png').default}
                  alt=''
                  onClick={this.switchEditor}
                />
              </Popover>
            </span>
            <Button onClick={this.publish} className='publish-btn'>
              发 布
            </Button>
            <img src={Store.userInfo.avatar} alt='avatar' />
            <span onClick={this.toHome}>主页</span>
          </div>
        </div>
        <Form layout='inline' style={{ width: '100%' }}>
          <Row style={{ marginBottom: '12px' }}>
            <Form.Item label='阅读权限'>
              <Radio.Group defaultValue='every' size='middle'>
                <Radio.Button value='personal'>个人</Radio.Button>
                <Radio.Button value='every'>所有</Radio.Button>
              </Radio.Group>
            </Form.Item>
            <Form.Item label='是否主页'>
              <Radio.Group defaultValue='0' size='middle'>
                <Radio.Button value='1'>是</Radio.Button>
                <Radio.Button value='0'>否</Radio.Button>
              </Radio.Group>
            </Form.Item>
            <Form.Item label='标签'>
              <span style={{ marginBottom: 16 }}>{tagChild}</span>
              {this.state.inputVisible && (
                <Input
                  ref={this.saveInputRef}
                  type='text'
                  size='small'
                  style={{ width: 78 }}
                  value={this.state.inputValue}
                  onChange={this.handleInputChange}
                  onBlur={this.handleInputConfirm}
                  onPressEnter={this.handleInputConfirm}
                />
              )}
              {!this.state.inputVisible && (
                <Tag onClick={this.showInput} className='site-tag-plus'>
                  <PlusOutlined /> New Tag
                </Tag>
              )}
            </Form.Item>
          </Row>
        </Form>
        <div className='descripition'>
          <TextArea
            placeholder='文章描述'
            value={this.state.form.descripition}
            onChange={this.descripitionChange}
          />
        </div>

        <div
          id='div1'
          style={this.state.editTools != 'text' ? { display: 'none' } : {}}
        ></div>
        <div style={this.state.editTools == 'text' ? { display: 'none' } : {}}>
          <TextArea id='editor' placeholder='请输入'></TextArea>
        </div>
      </div>
    )
  }
}
export default withRouter(Publish)
